import pickle
import base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request,reponse,user):
    """
    合并请求用户的购物车数据，将未登录保存在cookie里的保存到redis中
    遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    :param request: 用户的请求对象
    :param user: 当前登录的用户
    :param response: 响应对象，用于清楚购物车cookie
    :return:
    """

    # 1、获取cookie
    cart_cookie = request.COOKIES.get('cart_cookie')
    # 2、判断cookie是否存在
    if cart_cookie is None:
        return reponse
    # 3、解密cookie
    cart = pickle.loads(base64.b64decode(cart_cookie))
    # 4、判断字典是否为空
    if not cart:
        return reponse
    # 5、拆分字典
    data_dict = {}  # 保存hash数据
    data_list = []  # 保存选中状态的sku——id
    data_list_none = []  # 保存未选中状态的sku——id

    for sku_id, data in cart.items():
        data_dict[sku_id] = data['count']  # {14:1,15:2}
        if data['selected']:
            data_list.append(sku_id)
        else:
            data_list_none.append(sku_id)

    # 6、将拆分后的数据写入redis中
    conn = get_redis_connection('cart')
    conn.hmset('cart_%s' % user.id, data_dict)
    if data_list:
        conn.sadd('cart_selectes_%s' % user.id, *data_list)
    if data_list_none:
        conn.srem('cart_selectes_%s' % user.id, *data_list)
    # 7、删除cookie
    reponse.delete_cookie('cart_cookie')
    # 8、结果返回
    return reponse